package com.hyw.supply.utils;

import com.hyw.supply.model.vo.LoginVO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Date;
import java.util.Objects;

/**
 * 自定义token
 *
 * @author zzp
 * @date 2024/3/14 17:33
 */

public class CustomToken {
    /**
     * 盐值信息
     */
    private final static String SECRETKEY = "hyw-supply";

    /**
     * 创建token
     *
     * @param userId   用户id
     * @param userName 用户名称
     * @return
     */
    public static LoginVO createToken(String userId, String userName,Boolean admined,String enterprise) {
        String token = Jwts.builder()
                .setSubject(userId)
                .setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 1000*48))
                .signWith(SignatureAlgorithm.HS512, SECRETKEY)
                .compact();
        return new LoginVO("Bearer " + token, userName,admined,enterprise);
    }

    /**
     * 验证token
     *
     * @param token token
     * @return 获取token信息
     */
    public static String getTokenInfo(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRETKEY)
                .parseClaimsJws(token).getBody();
        if (claims != null && claims.getExpiration().before(new Date())) {
            throw new RuntimeException();
        }
        return Objects.requireNonNull(claims).getSubject();
    }

    /**
     * 获取账户id
     *
     * @return 账户id
     */
    public static String getAccountId() {
        return (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

}
